//
//  SJMessageListViewController.m
//  WSL
//
//  Created by CJ on 2018/2/3.
//  Copyright © 2018年 sanjuetech. All rights reserved.
//

#import "SJMessageListViewController.h"
#import "SJMessageCell.h"
#import "SJMessageItem.h"
#import "SJMyMsgApi.h"
#import "SJPushDeleteApi.h"


@interface SJMessageListViewController () <UITableViewDelegate, UITableViewDataSource>


@property (nonatomic ,strong) UITableView *tableView;
@property (nonatomic, assign) int page;
@property (nonatomic ,strong) NSMutableArray *dataArray;
@property (nonatomic, strong) UIView *navigationBarView;

@end

@implementation SJMessageListViewController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    [SJStatisticTool beginLogPageView:NSStringFromClass([self class])];
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    
    [SJStatisticTool endLogPageView:NSStringFromClass([self class])];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view
    
    self.page = 0;
    [self setupUI];
    [self loadNewData];

}

- (void)setupUI {
    
    [self.view addSubview:self.tableView];
    self.tableView.sd_layout.spaceToSuperView(UIEdgeInsetsZero);
    
//    [self.view addSubview:self.navigationBarView];
//
//    if (812 == SJScreenH) {
//        self.navigationBarView.sd_layout
//        .leftSpaceToView(self.view, SJLayoutFrame(0))
//        .topSpaceToView(self.view, SJLayoutFrame(40))
//        .heightIs(SJLayoutFrame(50))
//        .widthIs(SJScreenW);
//    } else {
//        self.navigationBarView.sd_layout
//        .leftSpaceToView(self.view, SJLayoutFrame(0))
//        .topSpaceToView(self.view, SJLayoutFrame(0))
//        .heightIs(SJLayoutFrame(50))
//        .widthIs(SJScreenW);
//    }
    
}

#pragma mark - getter

- (UIView *)navigationBarView{
    
    if (!_navigationBarView) {
        
        _navigationBarView = [UIView new];
        _navigationBarView.backgroundColor = [UIColor clearColor];
        
        UILabel *wordLabel = [UILabel new];
        wordLabel.textColor = SJColorHexString(@"#ffffff");
        wordLabel.font = [UIFont fontWithName:@"Helvetica" size:SJLayoutFrame(17)];
        wordLabel.textAlignment = NSTextAlignmentCenter;
        
        wordLabel.text = @"消息";
        [_navigationBarView addSubview:wordLabel];
        wordLabel.sd_layout
        .centerYEqualToView(_navigationBarView)
        .centerXEqualToView(_navigationBarView)
        .heightIs(SJLayoutFrame(27));
        [wordLabel setSingleLineAutoResizeWithMaxWidth:SJScreenW * .5];
        
    }
    return _navigationBarView;
}

- (NSMutableArray *)dataArray {
    
    if (!_dataArray) {
        
        _dataArray = [[NSMutableArray alloc] init];  // 分四个 Section
        
        
    }
    return _dataArray;
}

- (UITableView *)tableView {
    
    if (!_tableView) {
        
        _tableView = [[UITableView alloc] initWithFrame:self.view.bounds];
        _tableView.separatorColor = [UIColor clearColor];
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.backgroundColor = [UIColor clearColor];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.contentInset = UIEdgeInsetsMake(0, 0, 0, 0);
        
        [_tableView registerClass:[SJMessageCell class] forCellReuseIdentifier:NSStringFromClass([SJMessageCell class])];
        
        // header
        _tableView.mj_header = [SJDIYHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewData)];
        // footer
        _tableView.mj_footer = [SJDIYFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
        
        
    }
    return _tableView;
}

#pragma mark - Action

- (void)deleteAction:(MGSwipeTableCell *)cell {
    
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
    
    SJMessageItem *item = self.dataArray[indexPath.row];
    
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    parameters[@"token"] = [SJUserDefaults objectForKey:SJToken];
    parameters[@"msg_id"] = item.ID;
    
    SJPushDeleteApi *api = [[SJPushDeleteApi alloc] initWithParameters:parameters];
    [api startWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
        
        if ([api.responseObject[@"result"][@"err"] intValue] == 0) {
            
            [self.dataArray removeObject:item];
            [self.tableView deleteRowAtIndexPath:indexPath withRowAnimation:UITableViewRowAnimationFade];
        }
        
    } failure:^(YTKBaseRequest *request) {
        
    }];
    
}

#pragma mark - tableview delegate and datasource

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    // 查看消息详情
    SJMessageItem *item = self.dataArray[indexPath.row];
    
    UIView *messageView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SJLayoutFrame(361), SJLayoutFrame(361))];
    messageView.sd_cornerRadius = @(SJCornerRadius);
    messageView.clipsToBounds = YES;
    
    UIBlurEffect *blurEffect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleRegular];
    UIVisualEffectView *visualView = [[UIVisualEffectView alloc] initWithEffect:blurEffect];
    [messageView addSubview:visualView];
    visualView.sd_layout.spaceToSuperView(UIEdgeInsetsZero);
    visualView.sd_cornerRadius = @(SJCornerRadius);
    
    UILabel *titleLabel = [UILabel new];
    titleLabel.numberOfLines = 1;
    titleLabel.textColor = [UIColor whiteColor];
    titleLabel.font = [UIFont systemFontOfSize:SJLayoutFrame(16)];
    titleLabel.text = @"思藏官方";
    titleLabel.textAlignment = NSTextAlignmentCenter;
    
    [messageView addSubview:titleLabel];
    titleLabel.sd_layout
    .topSpaceToView(messageView, 0)
    .leftSpaceToView(messageView, 0)
    .rightSpaceToView(messageView, 0)
    .heightIs(SJLayoutFrame(39));
    
    UITextView *detailTextView = [UITextView new];
    detailTextView.font = [UIFont systemFontOfSize:SJLayoutFrame(14)];
    detailTextView.textColor = SJColorHexString(@"#ffffff");
    detailTextView.backgroundColor = [UIColor clearColor];
    detailTextView.textAlignment = NSTextAlignmentCenter;
    detailTextView.editable = NO;
    detailTextView.showsVerticalScrollIndicator = NO;
    detailTextView.text = item.message;
    
    [messageView addSubview:detailTextView];
    detailTextView.sd_layout
    .topSpaceToView(titleLabel, 0)
    .leftSpaceToView(messageView, SJLayoutFrame(10))
    .rightSpaceToView(messageView, SJLayoutFrame(10))
    .bottomSpaceToView(messageView, SJLayoutFrame(20));
    
//    WeakSelf;
    [LEEAlert alert].config
    .LeeCustomView(messageView)
    .LeeBackgroundStyleTranslucent(0)
    .LeeClickBackgroundClose(YES)
    .LeeCornerRadius(SJCornerRadius)
    .LeeHeaderColor([UIColor clearColor])
    .LeeMaxWidth(SJLayoutFrame(361))
    .LeeMaxHeight(SJLayoutFrame(361))
    .LeeHeaderInsets(UIEdgeInsetsMake(0, 0, 0, 0))
    .LeeShow();

}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    // 根据数据量显示或者隐藏footer
    self.tableView.mj_footer.hidden = (self.dataArray.count == 0);
    return self.dataArray.count;

}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    SJMessageCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([SJMessageCell class])];
    
    SJMessageItem *item = self.dataArray[indexPath.row];

    cell.item = item;
    
    MGSwipeButton *deleteButton = [MGSwipeButton new];
    [deleteButton setEdgeInsets:UIEdgeInsetsMake(SJMargin, 0, 0, SJMargin)];
    deleteButton.buttonWidth = SJLayoutFrame(92);
    
    UIView *bgView = [UIView new];
    bgView.sd_cornerRadius = @(SJCornerRadius);
    bgView.backgroundColor = SJColorHexString(@"#ffffff25");
    bgView.userInteractionEnabled = NO;
    [deleteButton addSubview:bgView];
    bgView.sd_layout.spaceToSuperView(UIEdgeInsetsMake(SJMargin, 0, 0, SJMargin));
    
    UILabel *deleteLabel = [UILabel new];
    deleteLabel.textColor = SJColorHexString(@"#99c7ff");
    deleteLabel.font = [UIFont systemFontOfSize:SJLayoutFrame(15)];
    deleteLabel.textAlignment = NSTextAlignmentCenter;
    deleteLabel.text = @"删除";
    [bgView addSubview:deleteLabel];
    deleteLabel.sd_layout.spaceToSuperView(UIEdgeInsetsZero);
    
    WeakSelf;
    deleteButton.callback = ^BOOL(MGSwipeTableCell * _Nonnull cell) {
        
        [weakSelf deleteAction:cell];
        return YES;
    };
    
    cell.rightButtons = @[deleteButton];
    cell.rightSwipeSettings.transition = MGSwipeStateSwipingRightToLeft;
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    return SJItemWH * 2 + SJMargin * 2;
}


#pragma mark - request

- (void)loadNewData {
    
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    parameters[@"token"] = [SJUserDefaults objectForKey:SJToken];
    parameters[@"rn"] = @"20";
    parameters[@"pn"] = @"0";
    
    SJMyMsgApi *api = [[SJMyMsgApi alloc] initWithParameters:parameters];
    
    if ([api loadCacheWithError:nil]) {
        
        if ([api.responseObject[@"result"][@"err"] intValue] == 0) {
            self.dataArray = [[NSArray modelArrayWithClass:[SJMessageItem class] json:api.responseObject[@"content"][@"data"]] mutableCopy];
            self.page = [api.responseObject[@"content"][@"cur"] intValue];
            
        } else {
            [self.dataArray removeAllObjects];
        }
    }
    
    [api startWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
        
        if ([api.responseObject[@"result"][@"err"] intValue] == 0) {
            self.dataArray = [[NSArray modelArrayWithClass:[SJMessageItem class] json:api.responseObject[@"content"][@"data"]] mutableCopy];
            self.page = [api.responseObject[@"content"][@"cur"] intValue];
            
        } else {
            [self.dataArray removeAllObjects];
        }
        
        [self.tableView reloadData];
        [self.tableView.mj_header endRefreshing];
        
    } failure:^(YTKBaseRequest *request) {
        [self.tableView reloadData];
        [self.tableView.mj_header endRefreshing];
    }];
    
}

- (void)loadMoreData {
    
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    parameters[@"token"] = [SJUserDefaults objectForKey:SJToken];
    parameters[@"rn"] = @"20";
    parameters[@"pn"] = [NSString stringWithFormat:@"%d", ++self.page];
    
    SJMyMsgApi *api = [[SJMyMsgApi alloc] initWithParameters:parameters];
    [api startWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {

        if ([api.responseObject[@"result"][@"err"] intValue] == 0) {

            [self.dataArray addObjectsFromArray:[NSArray modelArrayWithClass:[SJMessageItem class] json:api.responseObject[@"content"][@"data"]]];
            self.page = [api.responseObject[@"content"][@"cur"] intValue];

        } else {
            self.page--;
        }

        [self.tableView reloadData];
        [self.tableView.mj_footer endRefreshing];
        
    } failure:^(YTKBaseRequest *request) {
        [self.tableView reloadData];
        [self.tableView.mj_footer endRefreshing];
        self.page--;
    }];
}


@end

